//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package roadmap_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/roadmap_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type WhiteUserInfoDbItem struct {
	UserId     string `bson:"_id"`
	DefaultTag string `bson:"defaultTag"`
	UserDesc   string `bson:"userDesc"`
	CreateTime int64  `bson:"createTime"`
	UpdateTime int64  `bson:"updateTime"`
}

func (item *WhiteUserInfoDbItem) ToWhiteUserInfo() *roadmap_api.WhiteUserInfo {
	return &roadmap_api.WhiteUserInfo{
		UserId:     item.UserId,
		DefaultTag: item.DefaultTag,
		UserDesc:   item.UserDesc,
		CreateTime: item.CreateTime,
		UpdateTime: item.UpdateTime,
	}
}

type _WhiteUserDao struct {
	mc *mongo.Collection
}

func newWhiteUserDao(db *mongo.Database) (*_WhiteUserDao, error) {
	mc := db.Collection(db_ns.DB_NS_ROADMAP + "white_user")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"createTime", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_WhiteUserDao{mc: mc}, nil
}

func (db *_WhiteUserDao) Insert(ctx context.Context, dbItem *WhiteUserInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_WhiteUserDao) Exist(ctx context.Context, userId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": userId})
	return count > 0, err
}

func (db *_WhiteUserDao) Get(ctx context.Context, userId string) (*WhiteUserInfoDbItem, error) {
	retItem := &WhiteUserInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": userId}).Decode(retItem)
	return retItem, err
}

func (db *_WhiteUserDao) Remove(ctx context.Context, userId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": userId})
	return err
}

func (db *_WhiteUserDao) Count(ctx context.Context) (uint32, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{})
	return uint32(count), err
}

func (db *_WhiteUserDao) List(ctx context.Context, offset, limit int64) ([]*WhiteUserInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{}, options.Find().SetSkip(offset).SetLimit(limit).SetSort(bson.M{"createTime": 1}))
	if err != nil {
		return nil, err
	}
	retList := []*WhiteUserInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_WhiteUserDao) Update(ctx context.Context, userId, defaultTag, userDesc string, updateTime int64) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": userId}, bson.M{
		"$set": bson.M{
			"defaultTag": defaultTag,
			"userDesc":   userDesc,
			"updateTime": updateTime,
		},
	})
	return err
}
